//
//  MyCollectsArticleViewController.swift
//  weile
//
//  Created by LKM on 16/11/7.
//  Copyright © 2016年 LKM. All rights reserved.
//

import UIKit
import SnapKit
/**
 文章收藏
 */
class MyCollectsArticleViewController: BaseViewController,UITableViewDelegate,UITableViewDataSource  {
    
    var tableview: UITableView!
    
    
    
    var mListFooterLoadView :ListFooterLoadView!
    var refreshControl:UIRefreshControl!
//    var data:ArticlesTo?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        tableview = UITableView()
        tableview.backgroundColor = UIColor.clear
        
        self.view.addSubview(tableview)
        
        tableview.snp.makeConstraints { (cm:ConstraintMaker) in
            cm.top.equalTo(topLayoutGuide.snp.bottom)
            cm.bottom.equalToSuperview()
            cm.left.equalToSuperview()
            cm.right.equalToSuperview()
        }
        
        
        mListFooterLoadView = ListFooterLoadView.createView();
        self.tableview.tableFooterView=mListFooterLoadView;
        
        self.tableview.register(UINib(nibName:"NewArticlesItem", bundle: nil), forCellReuseIdentifier: "ArticlesItem")
        
        //tableview参数设置
        tableview.rowHeight = NewArticlesItem.getHeigth()//98.7//8+82+8+0.7
        tableview.separatorStyle = .none
        tableview.contentInset = UIEdgeInsetsMake(0, 0, MainTabBarHeight, 0)
        tableview.scrollIndicatorInsets = tableview.contentInset
        tableview.delegate=self;
        tableview.dataSource = self;
        //tableview参数设置  end
        
        // 添加刷新控件
        refreshControl = UIRefreshControl()
        //        refreshControl.attributedTitle = NSAttributedString(string: "松开后自动刷新")
        tableview.addSubview(refreshControl)
        refreshControl.addTarget(self, action: #selector(loadData(_:)), for: .valueChanged)
        // 添加刷新控件 end
        
        if loadData(false){
            refreshControl.beginRefreshing()
        }
        
        // Do any additional setup after loading the view.
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
//        navigationController?.setNavigationBarHidden(true, animated: false)
    }
    
    
    
    var listData: [MyCollectsItemTo] = Array();//
    var curPage = 1;//第一开始
    var isLoadIng = false;//是否加载中
    var isLoadAppending = false;//是否加载更多数据
    var hasMoreData=true;//是否有更多数据
    
    @discardableResult
    func loadData(_ isLoadAppend :Bool) -> Bool{
        if isLoadIng {
            return isLoadAppend == isLoadAppending;
        }
        self.isLoadAppending=isLoadAppend;
        isLoadIng=true
        
        if(isLoadAppend){
            mListFooterLoadView.setAppending()
        }else{
            mListFooterLoadView.setRefreing()
        }
        
        let taskSerialNumber=Api.MyCollectArticle(preTaskSerialNumber: nil,page: isLoadAppend ? (curPage + 1) : 1){ (re:ResponEntity) in
            self.isLoadIng=false;
            if(re.isSuccess()){
//                self.data = re.data as? ArticlesTo;
                let articlelist = re.data as? [MyCollectsItemTo];
                
                //数据是那些----
                let hasListData = !(CollectionHelp.isEmpty( articlelist )) //!(self.data?.prolist == nil);
                if(self.isLoadAppending){
                    self.curPage += hasListData ? 1 : 0;
                }else{
                    self.listData.removeAll();
                    self.curPage = 1;
                }
                self.listData += articlelist ?? Array();
                
                self.hasMoreData = hasListData
                if(self.hasMoreData){//这个是针对这个搜索，后台没做分页的情况
                    //打于等于20就是有下一页
                    self.hasMoreData = CollectionHelp.size(articlelist) >= LKMAPIListPageSize;
                }
                //没有更多数据了
                self.mListFooterLoadView.setNone(hasNextPage: hasListData)
                //数据是那些----end
                
                self.tableview.reloadData()
            }else{
                ViewHelp.showTipsView(containView: self.view, tips: re.msg);
            }
            self.refreshControl.endRefreshing()
        }
        taskAlls.append(taskSerialNumber);
        
        return true;
    }
    
    var taskAlls = [Int]();
    deinit {
        //界面退出肯定就不登陆咯
        Api.destroyTask(taskSerialNumbers: taskAlls);
    }
    
    
    
    
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    // MARK: - UITableViewDataSource
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.listData.count
    }
    
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let homeCell = tableView.dequeueReusableCell(withIdentifier: "ArticlesItem") as! NewArticlesItem//ArticlesItem
        homeCell.selectionStyle = .default
        
        let mArticlesItemTo=ArticlesItemTo.init(jsons: [:]);
        let o = self.listData[(indexPath as NSIndexPath).row]
        mArticlesItemTo?.ImgUrl=o.img;
        mArticlesItemTo?.Title=o.title;
        mArticlesItemTo?.Content=o.remark
        mArticlesItemTo?.Id=o.conid;
        homeCell.mArticlesItemTo = mArticlesItemTo;
        
        let count:Int=self.tableView( tableView, numberOfRowsInSection:1);
        if(indexPath.row+1>=count){
            //加载更多数据
            if hasMoreData{
                //一般到显示倒数第二个就会去加载
                loadData(true);
            }
            
        }
        
        
        return homeCell
    }
    // MARK: - UITableViewDelegate
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let o = self.listData[(indexPath as NSIndexPath).row]
        ActivityRequest.goArticleDetailController(navigationController!,o.id ?? "");
    }
    /*
     // MARK: - Navigation
     
     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
     // Get the new view controller using segue.destinationViewController.
     // Pass the selected object to the new view controller.
     }
     */
    
}
